package com.guangwei.phoneforelder.phonecallui

import android.os.Build
import android.telecom.Call
import android.telecom.InCallService
import androidx.annotation.RequiresApi
import com.guangwei.phoneforelder.ActivityStack

/**
 * 监听电话通信状态的服务，实现该类的同时必须提供电话管理的 UI
 *
 * @author aJIEw
 * @see PhoneCallActivity
 *
 * @see android.telecom.InCallService
 */
@RequiresApi(api = Build.VERSION_CODES.M)
class PhoneCallService : InCallService() {

    private val callback = object : Call.Callback() {
        override fun onStateChanged(call: Call, state: Int) {
            super.onStateChanged(call, state)

            when (state) {
                Call.STATE_ACTIVE -> {
                }

                Call.STATE_DISCONNECTED -> {
                    ActivityStack.instance.finishActivity(PhoneCallActivity::class.java)
                }
            }
        }
    }

    override fun onCallAdded(call: Call) {
        super.onCallAdded(call)

        call.registerCallback(callback)
        PhoneCallManager.call = call

        var callType: CallType? = null

        if (call.state == Call.STATE_RINGING) {
            callType = CallType.CALL_IN
        } else if (call.state == Call.STATE_CONNECTING) {
            callType = CallType.CALL_OUT
        }

        if (callType != null) {
            val details = call.details
            val phoneNumber = details.handle.schemeSpecificPart
            PhoneCallActivity.actionStart(this, phoneNumber, callType)
        }
    }

    override fun onCallRemoved(call: Call) {
        super.onCallRemoved(call)

        call.unregisterCallback(callback)
        PhoneCallManager.call = null
    }

    enum class CallType {
        CALL_IN,
        CALL_OUT
    }
}